package com.mio.scalademo

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

import scala.io.StdIn
import java.util.Date
class WorkerActor(actorRef: ActorRef, name:String) extends Actor {
  var wtime:Date = new Date()
  val masterActorRef: ActorRef = actorRef
  val workName:String = name
  // 接收消息并处理
  override def receive: Receive = {
    
    case "拜拜" => {
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
//      context.system.terminate()
    }
    
    case "sendHeartBeat" => {
      //worker定时发送心跳到master
      println(name +"发送心跳")
      masterActorRef ! name //给 MasterActor 发出消息
    }
  }
}

class Work(){
  var name:String =null;
}

class MasterActor() extends Actor {
  var workMap = scala.collection.mutable.Map[String,Date]()
  // 接收消息并处理
  override def receive: Receive = {
    
    case "拜拜" => {
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
//      context.system.terminate()
    }
    case "check" => {
      for (key<- workMap.keys) {
        var hbDate = workMap(key)
        if( (new Date()).getTime - hbDate.getTime >2000){
          println(key + " 掉线了")
           workMap -= key
        }
      }
    }
    case x:String =>{
      if(!workMap.contains(x)) {
        println(x + "注册成功")
      }
      workMap(x) = new Date()
    }
  }
}
object HeartBeatTest {
   def main(args: Array[String]): Unit = {
     val MyFactory = ActorSystem("myFactory")
      // 创建一个Master
       val masterActorRef = MyFactory.actorOf(Props[MasterActor], "masterActor")
      // 创Worker 并注册到Master
      val workActorRef1: ActorRef = MyFactory.actorOf(Props(new WorkerActor(masterActorRef,"workActor1")), "workActor1")
      val workActorRef2: ActorRef = MyFactory.actorOf(Props(new WorkerActor(masterActorRef,"workActor2")), "workActor2")
      
      masterActorRef ! "workActor1"
      masterActorRef ! "workActor2"
      Thread.sleep(1000)
      var i = 0;
         while (true) {
           i = i+1
           //Worker 定时发送心跳
           if(i<=3){
              workActorRef1 ! "sendHeartBeat"
           }
            workActorRef2 ! "sendHeartBeat"
            
             masterActorRef ! "check"
            // 休眠1000毫秒
            Thread.sleep(1000)
          }
   }
}